package com.apex.controller;


import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author George
 * @since 2023-06-24
 */
@RestController
public class UserController {

    @ApiOperation(value = "用户登录路径")
    @RequestMapping(value = {"/login"})
    public ModelAndView login(String username, String password, Model model,ModelAndView modelAndView) {
        //获取一个用户
        Subject subject = SecurityUtils.getSubject();
        // 封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        System.out.println(username);

        try {
            //执行登录的方法，如果没有异常就说明ok了
            subject.login(token);
            modelAndView.setViewName("BackEnd/index");
            model.addAttribute("msg","");
            return modelAndView;
        } catch (UnknownAccountException e) {//用户名不存在
            model.addAttribute("msg","用户名错误");
            System.out.println("账户错误");
            modelAndView.setViewName("BackEnd/login");
            return modelAndView;
        } catch (IncorrectCredentialsException e) {//密码不存在
            model.addAttribute("msg","密码错误");
            modelAndView.setViewName("BackEnd/login");
            System.out.println("密码错误");
            return modelAndView;
        }
    }


}

